package com.org.zp.ctrl.search;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.org.base.ctrl.ActivityTaskManager;
import com.org.base.ctrl.BaseActivity;
import com.org.base.util.HttpUtils;
import com.org.base.util.URLHelper;
import com.org.zp.R;
import com.org.zp.app.RecApp;
import com.org.zp.ctrl.login.LoginActivity;
import com.org.zp.ctrl.myzhaopin.CreateResumeActivity;
import com.org.zp.entity.search.PositionItems;

/**
 * 职位搜索--职位信息
 * 
 * @author Administrator
 * 
 */
public class PositionActivity extends BaseActivity {

	private TextView title;
	private Button back_btn;
	private Button enable_btn;
	private Button position;
	private Button company;
	private TextView position_1;
	private TextView position_2;
	private TextView position_3;
	private TextView position_4;
	private TextView position_5;
	private TextView position_6;
	private ProgressDialog progressDialog;
	private RecApp mApp;
	private LinearLayout guide_typesitem = null;

	private RadioButton apply_job;// 申请职位
	private RadioButton favorite_job;// 收藏职位
	private PositionItems positionItems = new PositionItems();
	private String mJob_number = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.postion_items);
		
		if (!(ActivityTaskManager.getInstance().containsName("PositionActivity"))) {
			ActivityTaskManager.getInstance().putActivity("PositionActivity",
					this);
		}

		mApp = (RecApp) getApplication();

		progressDialog = ProgressDialog.show(PositionActivity.this, "请等待...",
				"正在加载信息，请稍后...", true, true);
		title = (TextView) findViewById(R.id.headTitle);
		back_btn = (Button) findViewById(R.id.back);
		enable_btn = (Button) findViewById(R.id.top_right_button);
		position = (Button) findViewById(R.id.position_items);
		position.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				company.setSelected(false);
				company.setTextColor(Color.WHITE);
				company.setShadowLayer(1, 2, 2, R.color.black_yinying);
				position.setSelected(true);
				position.setTextColor(Color.BLACK);
				position.setShadowLayer(1, 2, 2, Color.WHITE);
				position_1.setText(positionItems.getJob_title());
				position_2.setText("月薪：" + positionItems.getSalary_range());
				position_3.setText("地点：" +  positionItems.getJob_city_region());
				position_4.setText("经验：" + positionItems.getWorking_exp());
				position_5.setText("人数：" + positionItems.getNumber());
				position_6.setText("工作职责："
						+ positionItems.getResponsibility());
			}
		});
		position.setSelected(true);
		
		company = (Button) findViewById(R.id.company_items);
		company.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				position.setSelected(false);
				position.setTextColor(Color.WHITE);
				position.setShadowLayer(1, 2, 2, R.color.black_yinying);
				company.setSelected(true);
				company.setTextColor(Color.BLACK);
				company.setShadowLayer(1, 2, 2, Color.WHITE);
				position_1.setText(positionItems.getCompany_name());
				position_2.setText("类别："
						+ positionItems.getCompany_property());
				position_3.setText("规模：" + positionItems.getCompany_size());
				position_4.setText("行业：" + positionItems.getIndustry());
				position_5.setText("地址：" + positionItems.getAddress());
				position_6.setText("公司介绍："
						+ positionItems.getCompany_desc().replaceAll(
								"&nbsp;", " "));
				
			}
		});
		
		guide_typesitem = (LinearLayout) findViewById(R.id.other_position);
		guide_typesitem.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PositionActivity.this,
						OtherPositionActivity.class);
				intent.putExtra("Com_number", positionItems.getCompany_number());
				startActivity(intent);
				
			}
		});
		
		position_1 = (TextView) findViewById(R.id.position_1);
		position_2 = (TextView) findViewById(R.id.position_2);
		position_3 = (TextView) findViewById(R.id.position_3);
		position_4 = (TextView) findViewById(R.id.position_4);
		position_5 = (TextView) findViewById(R.id.position_5);
		position_6 = (TextView) findViewById(R.id.position_6);
		back_btn.setText("  返回");
		back_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.e("TMG", "onclick");
				ActivityTaskManager.getInstance().removeActivity(
						"PositionActivity");
			}
		});
		title.setText("职位信息");
		enable_btn.setText("返回首页");
		// 返回首页
		enable_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.e("TMG", "onclick");
				ActivityTaskManager.getInstance().removeActivity(
						"PositionActivity");
				ActivityTaskManager.getInstance().removeActivity(
						"SearchJobResultActivity");
				ActivityTaskManager.getInstance().removeActivity(
						"SearchJobActivity");

			}
		});

		// 申请职位
		apply_job = (RadioButton) findViewById(R.id.apply_job);
		apply_job.setOnCheckedChangeListener(onChangeListener);
		// 收藏职位
		favorite_job = (RadioButton) findViewById(R.id.favorite_job);
		favorite_job.setOnCheckedChangeListener(onChangeListener);
		initdata();
	}
	
	class QueryPositionAsyncTask extends AsyncTask<String, Void, String> {
		
		@Override
		protected String doInBackground(String... params) {
			Map<String, String> map = new HashMap<String, String>(); // 登录时向服务器发送的参数
			
			
			map.put("act", "jobDetail");
			map.put("id", mJob_number);
			return HttpUtils.readHttp(params[0], map);// 网络操作，向服务器发送登录请求，获取返回信息

		}

		@Override
		protected void onPostExecute(String result) {

			Log.e("TMG", "position result = " + result);
			if (result == null || result.equals("")) {
				// 发送解析数据 消息
				Log.e("TMG", "searchPosition result = null");
				progressDialog.dismiss();
			} else if (result.equals("timeout")) {
				// 发送解析数据 消息
				Log.e("TMG", "searchPosition result = timeout");
				progressDialog.dismiss();
			} else {
				parseJson(result);
			}

		}

	}
	
	private void parseJson(String result){
		
		try {
			String succeed = new JSONObject(result).getString("succeed");
			if (succeed.equals("000")) {
				JSONObject json = new JSONObject(result);
				positionItems.setJob_number(json.getString("job_id"));
				positionItems.setCompany_number(json.getString("company_id"));
				positionItems.setJob_title(json.getString("job_name"));
				positionItems.setSalary_range(json.getString("job_wage_cn"));
				positionItems.setJob_city_region(json.getString("job_district_cn"));
				positionItems.setWorking_exp(json.getString("job_experience_cn"));
				positionItems.setNumber(json.getString("job_amount"));
				positionItems.setResponsibility(json.getString("job_contents"));
				
				positionItems.setCompany_name(json.getString("company_companyname"));
				positionItems.setCompany_property(json.getString("company_nature_cn"));
				positionItems.setIndustry(json.getString("company_trade_cn"));
				positionItems.setCompany_size(json.getString("company_scale_cn"));
				positionItems.setAddress(json.getString("company_address"));
				positionItems.setCompany_desc(json.getString("company_contents"));
				
				
				company.setTextColor(Color.WHITE);
				company.setShadowLayer(1, 2, 2, R.color.black_yinying);
				position.setSelected(true);
				position.setTextColor(Color.BLACK);
				position.setShadowLayer(1, 2, 2, Color.WHITE);
				position_1.setText(positionItems.getJob_title());
				position_2.setText("月薪：" + positionItems.getSalary_range());
				position_3.setText("地点：" + positionItems.getJob_city_region());
				position_4.setText("经验：" + positionItems.getWorking_exp());
				position_5.setText("人数：" + positionItems.getNumber());
				position_6.setText("工作职责："
						+ positionItems.getResponsibility());
				
			} else {
				
			}
			progressDialog.dismiss();

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void initdata() {
		Intent i = getIntent();
		mJob_number = i.getStringExtra("Job_number");
		new QueryPositionAsyncTask().execute(URLHelper.mPrefix);
	}

	OnCheckedChangeListener onChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (!isChecked)
				return;
			if (null == positionItems) {
				Toast toast = Toast.makeText(PositionActivity.this, "职位初始化失败!",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return;
			}
			Intent intent = null;
			switch (buttonView.getId()) {
			case R.id.apply_job:// 申请职位
				apply_job.setChecked(false);
				apply_job.clearFocus();
				if(!mApp.user.getuID().equals("")){
					if(mApp.user.getResume().size() == 0){
						Toast toast = Toast.makeText(PositionActivity.this, "您尚未创建简历，请创建简历!",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						
						intent = new Intent(PositionActivity.this,
								CreateResumeActivity.class);
						startActivity(intent);
						
						ActivityTaskManager.getInstance().removeActivity(
								"PositionActivity");
						ActivityTaskManager.getInstance().removeActivity(
								"SearchJobResultActivity");
						ActivityTaskManager.getInstance().removeActivity(
								"SearchJobActivity");
					}else{
						new ApplyJobAyncTask().execute(URLHelper.mPrefix);
					}
					
				}else{
					showNotLoginPrompt("您尚未登录,不能进行职位申请.");
				}
				
				break;
			case R.id.favorite_job:// 收藏职位
				favorite_job.setChecked(false);
				favorite_job.clearFocus();
				if(!mApp.user.getuID().equals("")){
					new FavoriteJobAyncTask().execute(URLHelper.mPrefix);
				}else{
					showNotLoginPrompt("您尚未登录,不能进行职位收藏.");
				}
				
				break;
			}
		}
	};

	public void showNotLoginPrompt(String str) {
		final AlertDialog dialog = new AlertDialog.Builder(this).create();
		dialog.setMessage(str);
		dialog.setTitle("提示");
		dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "放弃",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		dialog.setButton(DialogInterface.BUTTON_POSITIVE, "登录",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						apply_job.setChecked(false);
						Intent intent = new Intent(PositionActivity.this,
								LoginActivity.class);
						intent.putExtra("type", "1");
						startActivity(intent);
					}
				});
		dialog.show();
	}

	private class ApplyJobAyncTask extends AsyncTask<String, Void, String> {
		
		@Override
		protected String doInBackground(String... params) {
			Map<String, String> map = new HashMap<String, String>(); // 登录时向服务器发送的参数
			
			Log.e("TMG", "Job id = " + mJob_number);
			Log.e("TMG", "resume id = " + mApp.user.getResume().get(0).getResume_id());
			
			map.put("act", "applyJob");
			map.put("jobId", mJob_number);
			map.put("uid", mApp.user.getuID());
			map.put("resumeId", mApp.user.getResume().get(0).getResume_id());
			return HttpUtils.readHttp(params[0], map);// 网络操作，向服务器发送登录请求，获取返回信息

		}

		@Override
		protected void onPostExecute(String result) {
			
			Log.e("TMG", "apply result = " + result);
			
			progressDialog.dismiss();

			if (result == null || result.equals("")) {
				
			} else if (result.equals("timeout")) {
				
			} else {
				try { 
					String succeed = new JSONObject(result).getString("succeed");
					if (succeed.equals("000")) {
						Toast toast = Toast.makeText(PositionActivity.this, "申请成功!",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}else{
						Toast toast = Toast.makeText(PositionActivity.this, "申请失败!",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
		
	}

	private class FavoriteJobAyncTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			Map<String, String> map = new HashMap<String, String>(); // 登录时向服务器发送的参数
			
			
			map.put("act", "userFavoritesJob");
			map.put("jobId", mJob_number);
			map.put("uid", mApp.user.getuID());
			return HttpUtils.readHttp(params[0], map);// 网络操作，向服务器发送登录请求，获取返回信息

		}

		@Override
		protected void onPostExecute(String result) {
			
			progressDialog.dismiss();

			if (result == null || result.equals("")) {
				
			} else if (result.equals("timeout")) {
				
			} else {
				try { 
					String succeed = new JSONObject(result).getString("succeed");
					if (succeed.equals("000")) {
						Toast toast = Toast.makeText(PositionActivity.this, "收藏成功!",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}else{
						Toast toast = Toast.makeText(PositionActivity.this, "收藏失败!",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
	}

}
